package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     * @param orderSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO orderSubmitDTO) {
        //1.解决业务异常（购物车为空，地址溥为空）
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(userId);
        if(shoppingCartList == null){
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        AddressBook addressBook = new AddressBook();

        addressBook.setId(orderSubmitDTO.getAddressBookId());
        addressBook.setUserId(userId);
        List<AddressBook> addressBookList = addressBookMapper.list(addressBook);
        if(addressBookList == null){
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //2.处理订单表-->插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(orderSubmitDTO,orders);
        //订单号
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
        orders.setStatus(Orders.PENDING_PAYMENT);
        //下单用户id
        orders.setUserId(userId);
        //地址
        orders.setAddress(addressBookList.get(0).getDetail());
        //收货人
        orders.setConsignee(addressBookList.get(0).getConsignee());
        //手机号
        orders.setPhone(addressBookList.get(0).getPhone());
        //下单时间
        orders.setOrderTime(LocalDateTime.now());
        //支付状态 0未支付 1已支付 2退款
        orders.setPayStatus(Orders.UN_PAID);
        //插入数据表
        orderMapper.insert(orders);

        //3.处理订单明细表-->插入多条数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        shoppingCartList.stream()
                .forEach(shoppingCart -> {
                    OrderDetail orderDetail = new OrderDetail();
                    BeanUtils.copyProperties(shoppingCart, orderDetail);
                    orderDetail.setOrderId(orders.getId());
                    orderDetailList.add(orderDetail);
                });
        orderDetailMapper.insertBatch(orderDetailList);

        //4.清空用户购物车数据
        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());

        //5.返回OrderSubmitVO
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO(orders.getId(), orders.getNumber(), orders.getAmount(), orders.getOrderTime());

        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);


        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
//    public void paySuccess(String outTradeNo) {
//
//        // 根据订单号查询订单
//        Orders ordersDB = orderMapper.getByNumber(outTradeNo);
//
//        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
//        Orders orders = Orders.builder()
//                .id(ordersDB.getId())
//                .status(Orders.TO_BE_CONFIRMED)
//                .payStatus(Orders.PAID)
//                .checkoutTime(LocalDateTime.now())
//                .build();
//
//        orderMapper.update(orders);
//    }
    public void paySuccess(String orderNumber) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(orderNumber);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //向客户端发送消息
        Map map = new HashMap();
        map.put("type", 1);    //1表示来单，2表示催单
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号：" + orderNumber);
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 历史订单分页查询
     * TODO 该部分判断是用户端请求还是客户端请求可以再优化
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageFindOrder(OrdersPageQueryDTO ordersPageQueryDTO) {
        //开始分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //查询订单数据
        Page<Orders> page = orderMapper.FindOrders(ordersPageQueryDTO);

        //获取数据总条数
        long total = page.getTotal();
        //获取所有数据对象
         List<Orders> result = page.getResult();

        result.stream()
                .forEach(orders -> {
                    orders.setOrderDetailList(orderDetailMapper.selectByOrderId(orders.getId()));
                });

        //封装PageResult对象并返回
        PageResult pageResult = new PageResult(total, result);

        return pageResult;
    }

    /**
     * 订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO findOrderDetail(Long id) {
        //查询订单数据
        Orders orders = orderMapper.findById(id);
        //查询订单对于的订单详情
        List<OrderDetail> orderDetail = orderDetailMapper.selectByOrderId(id);
        //封装VO对象并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetail);
        return orderVO;
    }

    /**
     * 订单取消
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        //添加订单取消原因
        orderMapper.updateCancelReasonByOrderId(ordersCancelDTO);
        //修改订单状态
        Integer status = 6;
        orderMapper.updateStatusByOrderId(status,ordersCancelDTO.getId());
    }

    /**
     * 订单拒绝
     * TODO 退款未实现
     * @param ordersCancelDTO
     */
    @Override
    public void rejection(OrdersCancelDTO ordersCancelDTO) {
        //添加订单拒绝原因
        orderMapper.updateRejecttionReasonByOrderId(ordersCancelDTO);
        //判断是否付款
        Orders orders = orderMapper.findById(ordersCancelDTO.getId());
        if(orders.getPayStatus() == 1){
            //退款
            System.out.println("退款成功");
        }
        //修改订单状态
        Integer status = 6;
        orderMapper.updateStatusByOrderId(status,ordersCancelDTO.getId());
    }

    /**
     * 订单确认
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
       //修改订单状态
       Integer status = 3;
       orderMapper.updateStatusByOrderId(status,ordersConfirmDTO.getId());
    }

    /**
     * 订单派送
     * @param id
     */
    @Override
    public void delivery(Long id) {
        //修改订单状态
        Integer status = 4;
        orderMapper.updateStatusByOrderId(status,id);
    }

    /**
     * 订单完成
     * @param id
     */
    @Override
    public void complete(Long id) {
       //修改订单状态
       Integer status = 5;
       orderMapper.updateStatusByOrderId(status,id);
    }

    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        //查询已接单的订单数据
        orderStatisticsVO.setConfirmed(orderMapper.findByStatus(3));
        //查询派送中的订单数据
        orderStatisticsVO.setDeliveryInProgress(orderMapper.findByStatus(4));
        //查询待接单的订单数据
        orderStatisticsVO.setToBeConfirmed(orderMapper.findByStatus(2));
        return orderStatisticsVO;
    }
}
